/**
 * 下载
 */
import axios from 'axios'
import { getToken } from '@/utils/auth'
import {ElMessage, ElNotification} from 'element-plus'
import { servicesLoading } from './loading'


export async function updateWord   ({url, params,fileName },){
  try {
    const res = await axios.request({
      method: 'post',
      params,
      responseType: "blob",
      url,
      headers: {
        Accept: "application/json",
        Authorization: `Bearer ${getToken()}`,
        "Content-Type": "application/json; charset=utf-8;",
        withCredentials: true,
      },
    });
    if (res.data.type !== "application/json") {
      return convertRes2Blob(res,fileName);
    } else {
      const enc = new TextDecoder('utf-8');
      res.data.arrayBuffer().then(buffer => {
        const data = JSON.parse(enc.decode(new Uint8Array(buffer))) || {};
        console.log(data)
        ElNotification({
          type: "error",
          title: data.msg,
          duration: 1000
        })
      })
    }
  } catch (err) {
    console.error(err);
  }

}

/**
 * Promise转化Blob类型
 * @param {response} axios返回的Promise
 */
function convertRes2Blob(response,fileName) {
  // 提取文件名
//   const fileName = decodeURI(get(response.headers['content-disposition'].match(
//     /filename\*=(.*)/
//   ), '1', '')).split("''")[1]
  // 将二进制流转为blob
  const blob = new Blob([response.data], { type: 'application/octet-stream' })
  if (typeof window.navigator.msSaveBlob !== 'undefined') {
    // 兼容IE，window.navigator.msSaveBlob：以本地方式保存文件
    window.navigator.msSaveBlob(blob, fileName)
  } else {
    // 创建新的URL并指向File对象或者Blob对象的地址
    const blobURL = window.URL.createObjectURL(blob)
    // 创建a标签，用于跳转至下载链接
    const tempLink = document.createElement('a')
    tempLink.style.display = 'none'
    tempLink.href = blobURL
    tempLink.setAttribute('download', fileName)
    // 兼容：某些浏览器不支持HTML5的download属性
    if (typeof tempLink.download === 'undefined') {
      tempLink.setAttribute('target', '_blank')
    }
    // 挂载a标签
    document.body.appendChild(tempLink)
    tempLink.click()
    document.body.removeChild(tempLink)
    // 释放blob URL地址
    window.URL.revokeObjectURL(blobURL)
  }
}



//定义导出统一的方法
export function updateMethod(data: any) {
  const loading = servicesLoading({ fullscreen: true })

  axios({
    method: data.method,
    url: data.url,
    responseType: 'blob',
    headers: {
      Authorization: 'Bearer ' + getToken(),
    },
    data: data.data,
  }).then((res) => {
    // const blob = new Blob([res.data],{ type: 'application/vnd.ms-excel' })
    const blob = new Blob([res.data], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    })
    const link = document.createElement('a')
    link.style.display = 'none'
    link.href = URL.createObjectURL(blob)
    link.download = data.fileName //下载的文件名
    document.body.appendChild(link)
    link.click()
    URL.revokeObjectURL(link.href) // 释放URL 对象
    document.body.removeChild(link)
    console.log(res, '导出结果')
    loading.close()

    if (res.status == 200) {
      ElMessage({
        message: '下载模版成功',
        type: 'success',
      })
    } else {
      ElMessage({
        message: '下载模版异常',
        type: 'warning',
      })
    }
  })
}
// 下载模板 GET方法
export function downloadMethod(data: any) {
  axios({
    method: data.method,
    url: `${data.url}${data.params ? '?' + data.params : ''}`,
    responseType: 'blob',
    headers: {
      Authorization: 'Bearer ' + getToken(),
    },
    params: data.params ? data.params : '',
  }).then((res) => {
    const blob = new Blob([res.data], { type: 'application/vnd.ms-docx' })
    const link = document.createElement('a')
    link.style.display = 'none'
    link.href = URL.createObjectURL(blob)
    link.download = data.fileName //下载的文件名
    document.body.appendChild(link)
    link.click()
    URL.revokeObjectURL(link.href) // 释放URL 对象
    document.body.removeChild(link)
    ElMessage.success({
      message: '下载成功',
      type: 'success',
    })
  })
}

// 下载word卡片
export function downloadCardMethod(data: any) {
  axios({
    method: data.method,
    url: data.url,
    responseType: 'blob',
    headers: {
      Authorization: 'Bearer ' + getToken(),
    },
    data: data.data,
  }).then((res) => {
    const blob = new Blob([res.data], { type: 'application/octet-stream;charset=UTF-8' })
    const link = document.createElement('a')
    link.style.display = 'none'
    link.href = URL.createObjectURL(blob)
    link.download = data.fileName //下载的文件名
    document.body.appendChild(link)
    link.click()
    URL.revokeObjectURL(link.href) // 释放URL 对象
    document.body.removeChild(link)
    ElMessage.success({
      message: '下载成功',
      type: 'success',
    })
  })
}
// 是否禁用锁定判断
export function lockBtnDisabled(row) {
  return true
  return row?.status !== 2 || row?.dataLock !== 1
}

export const downloadFile: (source: string, name: string) => void = (source, name) => {
  const aDom = document.createElement('a')
  aDom.download = name
  aDom.href = source
  aDom.dispatchEvent(new MouseEvent('click', {}))
}

//通过value遍历字典name
export const ergodicDickName = (val, list) => {
  console.log(val,list,'list');

  let name
  list?.forEach((element) => {
    if (element.itemValue == val) {
      name = element.itemText
      // console.log('return',name);
      return
    }
  })
  return name
}
//通过value遍历字典name
export const ergodicListName = (val, list, valKey, nameKey) => {
  let name
  list?.forEach((element) => {
    if (element[valKey] == val) {
      name = element[nameKey]
      return
    }
  })
  // console.log(name)
  return name
}

//遍历机构单位
export const ergodicOrg = (orgList) => {
  orgList?.forEach((element) => {
    element.label = element.name
    element.value = element.id
    if (element.children) {
      ergodicOrg(element.children)
    }
  })
}

//遍历树形数据name
export const ergodicTreeName = (x, orgList, val, valKey, labelKey) => {
  // console.log(orgList,'orgList');
  for (const element of orgList) {
    if (element[valKey] == val) {
      x = element[labelKey]
      console.log('x',x)
      return x
    }
    if (element.children) {
      x = ergodicTreeName(x, element.children, val, valKey, labelKey)
    }
  }
  // console.log('return',x);
  return x
}

export const objToString = (obj) => {
  const str = Object.keys(obj)
    .map((k) => [k, obj[k]].join('='))
    .join('&')
  console.log(str)
  return str
}
export const stringToObj = (str) => {
  const obj = eval('(' + str + ')')
  console.log(obj)
  return obj
}
export const fontSizeRem = (res) => {
  const clientHeight =
    window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight
  if (!clientHeight) return
  const fontSize = 100 * (clientHeight / 1080)
  return (res * fontSize) as any
}

// 判断的是否是JSON字符串
export const type = (str) => {
  if (typeof str == 'string') {
    try {
      const obj = JSON.parse(str)
      // 等于这个条件说明就是JSON字符串 会返回true
      if (typeof obj == 'object' && obj) {
        return true
      } else {
        //不是就返回false
        return false
      }
    } catch (e) {
      return false
    }
  }
  return false
}

// 根据一个原数组树 - 获取指定级别及指定级别以下的数据，过滤掉级别以外的数据
export const filterDepthTree = (data: Record<string, any>[], depth: number) => {
  // 创建一个新数组来存储结果
  const result: Record<string, any>[] = [];
  // 定义一个递归函数来遍历树
  const traverse = (node: Record<string, any> | null, level = 1): Record<string, any> | null => {
    // 如果节点有子节点
    if (node && node.children?.length) {
      node.children = node.children.map((child: Record<string, any> | null) => {
        // 递归调用遍历函数
        return traverse(child, level + 1);
      }).filter((child: Record<string, any> | null) => !!child);  // 过滤掉那些被丢弃的节点
      // 如果当前节点的级别小于depth-1级，并且没有子节点，则丢弃当前节点
      if (level < depth - 1 && !node.children?.length) {
        return null;
      }
    } else if (level < depth) {
      // 如果当前节点的级别小于depth级，并且没有子节点，则丢弃当前节点
      return null;
    }
    return node;
  }
  // 遍历树的每个节点
  for (const node of data) {
    const newNode = traverse(node);
    newNode && result.push(newNode);
  }
  // 返回结果数组
  return result;
}

export const NumberCheck = (num) => {
  console.log(num, 'num')

  let str = num
  const len1 = str.substr(0, 1)
  const len2 = str.substr(1, 1)
  //如果第一位是0，第二位不是点，就用数字把点替换掉
  if (str.length > 1 && len1 == 0 && len2 != '.') {
    str = str.substr(1, 1)
  }
  //第一位不能是.
  if (len1 == '.') {
    str = ''
  }
  //限制只能输入一个小数点
  if (str.indexOf('.') != -1) {
    const str_ = str.substr(str.indexOf('.') + 1)
    if (str_.indexOf('.') != -1) {
      str = str.substr(0, str.indexOf('.') + str_.indexOf('.') + 1)
    }
  }
  //正则替换，保留数字和小数点
  str = str.replace(/[^\d^\.]+/g, '')
  //如果需要保留小数点后两位，则用下面公式
  str = str.replace(/\.\d\d\d$/, '')
  return str
}

